package com.tyt.lelan;

import java.util.Date;

import android.app.Activity;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CursorAdapter;
import android.widget.GridView;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.tyt.lelan.adapter.AllFeedsAdapter;
import com.tyt.lelan.adapter.BoardAdapter;
import com.tyt.lelan.adapter.FeedAdapter;
import com.tyt.lelan.adapter.MyFeedAdapter;
import com.tyt.lelan.provider.DatabaseHelper;
import com.tyt.lelan.provider.FeedsData;
import com.tyt.lelan.provider.FeedsData.AllFeedsColumns;
import com.tyt.lelan.provider.FeedsData.EntryColumns;
import com.tyt.lelan.provider.FeedsData.MyFeedsColumns;
import com.tyt.lelan.utils.AsycItemFreshLoder;
import com.tyt.lelan.utils.InitialDataBase;
import com.tyt.lelan.utils.Property;
import com.tyt.lelan.utils.PubDateParser;
import com.tyt.lelan.view.ScrollLayout;

public class MainActivity extends Activity implements OnClickListener{
	
    private static final String TAG = "乐览";
    private int     mMode;
    private View 	mButton_back;
    private View  	 mTopBarButtons;
    private View    delFeedDv;
    private TextView   mTextSecond;
    private TextView   mTextFirst;
    private View       mProgress;
    
    private final int LOAD_ALLBOARDS=0;
    private final int LOAD_ALLFEEDS=1;
    private final int LOAD_MYFEEDS=2;
    private final int DEL_MYFEEDS=3;
    private final int UPDATE_ENTRY=4;
    private final int UPDATE_ENTRY_OK=5;
    
    private final int MODE_MYFEEDS=0;
    private final int MODE_ALLFEEDS=2;
    private final int MODE_ALLBOARDS=1;
    private final int MODE_DELMYFEEDS=3;
    
    private final int DIALOG_DELMYFEEDS=0;
    
    private Bundle mDelFeed;
    private  AllFeedsAdapter mAllFeedsAdapter;
   
    
	/** Called when the activity is first created. */
    ScrollLayout mFeedView;
    LayoutAnimationController controller;
    @Override    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(  R.layout.main);
        
        mFeedView = (ScrollLayout)findViewById(R.id.feedView);
        mButton_back =  findViewById(R.id.btn_back);
        mButton_back.setOnClickListener(this);

        mTopBarButtons=findViewById(R.id.layout_topbar_btns);
        mTextSecond=(TextView) findViewById(R.id.tv_title_second);
        mTextFirst=(TextView) findViewById(R.id.tv_title_first);
        mProgress=findViewById(R.id.progress_updateprogress);
        
        findViewById(R.id.btn_add).setOnClickListener(this);
        findViewById(R.id.btn_del).setOnClickListener(this);
        findViewById(R.id.btn_update).setOnClickListener(this);
		initViews();
	}

    /**
     *初始化数据库线程
     * @author yyj
     *
     */
    private class DataBaseload extends AsyncTask<String,Integer,Void>
	{
		
		@Override
		protected void onPreExecute() {
			
			super.onPreExecute();
			
		}
		
		@Override
		protected void onPostExecute(Void result) {
			
			Message msg=new Message();
	    	msg.what=LOAD_MYFEEDS;
	    	handler.sendMessage(msg);
	    	  
			super.onPostExecute(result);
		}
		

		@Override
		protected Void doInBackground(String... params) {
			// TODO Auto-generated method stub	
			
			SQLiteDatabase db=new DatabaseHelper(MainActivity.this).getWritableDatabase();
	    	if(db.getVersion()==1){
	    		InitialDataBase intial=new InitialDataBase(getContentResolver());
	    		intial.initalMyFeed();
	    		intial.initialAllFeeds();
	    		intial.initialIcon();
	    		intial.initialCategory();
	    		db.setVersion(2);
	    	}
	    	
	    	db.close();			
			return null;
		}
		
		
	}

   
    
    public void initViews(){
    	
    	new DataBaseload().execute();  
    	controller = AnimationUtils.loadLayoutAnimation(this, R.anim.layout_grid_fade);
	}
    
    private final OnItemClickListener gridItemClick=new OnItemClickListener(){

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			int  index;
			Message msg=new Message();
			Bundle data=new Bundle();
			Cursor cursor = (Cursor) parent.getAdapter().getItem(position);
			switch (mMode){
	
			case MODE_MYFEEDS:   
				
				if("更多内容".equals(((TextView) view.findViewById(R.id.tv_Name)).getText())){
				
					msg.what=LOAD_ALLBOARDS;
					handler.sendMessage(msg);
				}
				else{
					
					Intent i=new Intent();
					i.setClass(MainActivity.this, RssItemListActivity.class);
					data.putInt("id", cursor.getInt(cursor.getColumnIndex(FeedsData.MyFeedsColumns.RSS_ID)));
					data.putString("link", cursor.getString(cursor.getColumnIndex(FeedsData.MyFeedsColumns.LINK)));
					data.putString("category", cursor.getString(cursor.getColumnIndex(FeedsData.MyFeedsColumns.CATEGORY)));
					data.putString("name", cursor.getString(cursor.getColumnIndex(FeedsData.NAME)));
					data.putBoolean("online", false);
					i.putExtras(data);
					startActivity(i);
				}
				break;
			case MODE_ALLBOARDS:
				index=cursor.getColumnIndex(FeedsData.NAME);
				String board=cursor.getString(index);
				
				msg.what=LOAD_ALLFEEDS;
				
				data.putString("board", board);
				msg.setData(data);
				handler.sendMessage(msg);
				break;
			case MODE_ALLFEEDS:
				
				Intent i=new Intent();
				i.setClass(MainActivity.this, RssItemListActivity.class);
				
				data.putInt("id", cursor.getInt(cursor.getColumnIndex(AllFeedsColumns._ID)));
				data.putString("link", cursor.getString(cursor.getColumnIndex(AllFeedsColumns.LINK)));
				data.putString("category", cursor.getString(cursor.getColumnIndex(AllFeedsColumns.CATEGORY)));
				data.putString("name", cursor.getString(cursor.getColumnIndex(FeedsData.NAME)));
				data.putInt("selected", cursor.getInt(cursor.getColumnIndex(AllFeedsColumns.SELECTED)));
				data.putString("icon_name", cursor.getString(cursor.getColumnIndex(AllFeedsColumns.ICON_NAME)));
				data.putBoolean("online", true);
				i.putExtras(data);
				startActivity(i);
				break;
			case MODE_DELMYFEEDS:
				
				String name=(String) ((TextView) view.findViewById(R.id.tv_Name)).getText();
				
				if("未读新闻".equals(name)
						||"乐视新闻".equals(name)
						||"热点推荐".equals(name)
						||"历史今天".equals(name)){
				
					//提示无法删除
					
				}
				else{
					//
					
					data.putInt("id", cursor.getInt(cursor.getColumnIndex(FeedsData.MyFeedsColumns.RSS_ID)));
					data.putString("link", cursor.getString(cursor.getColumnIndex(FeedsData.MyFeedsColumns.LINK)));
					data.putString("category", cursor.getString(cursor.getColumnIndex(FeedsData.MyFeedsColumns.CATEGORY)));
					data.putString("name", cursor.getString(cursor.getColumnIndex(FeedsData.NAME)));
					data.putString("icon_name", cursor.getString(cursor.getColumnIndex(FeedsData.MyFeedsColumns.ICON_NAME)));
					msg.what=DEL_MYFEEDS;
					msg.setData(data);
					handler.sendMessage(msg);
					
				}
				
				break;
			default:
					break;
			}
		}
    	
    };
    
    protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch(id){
		case DIALOG_DELMYFEEDS:
			
			final Dialog mAddFeedDialog = new Dialog(this);
			delFeedDv = LayoutInflater.from(this).inflate(R.layout.dialog_addfeed, null);
			delFeedDv.findViewById(R.id.btn_addFeedok).setOnClickListener(this);
			delFeedDv.findViewById(R.id.btn_addFeedcancel).setOnClickListener(this);
			mAddFeedDialog.setContentView(delFeedDv);
			return mAddFeedDialog;
		
		default:
		break;
		}
		return null;
	}
    
    private Handler handler = new Handler() 
	{
		@Override
		public void handleMessage(Message msg) 
		{
			switch(msg.what){
			case UPDATE_ENTRY_OK:
				
				Toast.makeText(MainActivity.this, "update ", Toast.LENGTH_SHORT);
				mProgress.setVisibility(View.GONE);
				break;
			case UPDATE_ENTRY:
				
				mProgress.setVisibility(View.VISIBLE);
				updateEntry();
				
				break;
			case DEL_MYFEEDS:
				mDelFeed=msg.getData();
				showDialog(DIALOG_DELMYFEEDS);
				((TextView)delFeedDv.findViewById(R.id.tv_addFeed)).setText("删除订阅\n"+mDelFeed.getString("name"));		
				break;
		
			case LOAD_ALLBOARDS:
				setAllBoardsView();
				mButton_back.setVisibility(View.VISIBLE);
				mTopBarButtons.setVisibility(View.GONE);
				mTextSecond.setText(" >> 订阅分类");
				mTextFirst.setText("添加订阅");
				break;
			case LOAD_ALLFEEDS:		
				String board=msg.getData().getString("board");
				setAllFeedsView(board);
				mTextSecond.setText(mTextSecond.getText()+" >> 订阅列表 ");
				mTopBarButtons.setVisibility(View.GONE);
				break;
			case LOAD_MYFEEDS:
				setMyFeedsView();
				mButton_back.setVisibility(View.GONE);
				mTopBarButtons.setVisibility(View.VISIBLE);
				mTextSecond.setText("新闻阅读器 1.0");
				mTextFirst.setText("乐览");
				break;
				
			default:
				break;
			}
		}
	};

	@Override
	public void onClick(View v) {

		// TODO Auto-generated method stub
		Message msg=new Message();
		
		switch (v.getId()){
		
		case R.id.btn_update:
			
			msg.what=UPDATE_ENTRY;
			handler.sendMessage(msg);
			break;
		case R.id.btn_add:		
			msg.what=LOAD_ALLBOARDS;
			handler.sendMessage(msg);
	    	
			break;
		case R.id.btn_back:
		
			switch(mMode){
			case MODE_ALLFEEDS:
				msg.what=LOAD_ALLBOARDS;
				handler.sendMessage(msg);
				break;
			case MODE_ALLBOARDS:
				msg.what=LOAD_MYFEEDS;
				handler.sendMessage(msg);
				break;
			case MODE_DELMYFEEDS:
				msg.what=LOAD_MYFEEDS;
				handler.sendMessage(msg);
				break;
			}
		case R.id.btn_del:
			
			mMode=MODE_DELMYFEEDS;
			mTopBarButtons.setVisibility(View.GONE);
			mTextSecond.setText("删除订阅");
			mTextFirst.setText("");
			mButton_back.setVisibility(View.VISIBLE);
			
			break;
		case R.id.btn_addFeedok:
			
			delMyFeed(mDelFeed);
			dismissDialog(DIALOG_DELMYFEEDS);
			Toast.makeText(MainActivity.this, "删除订阅"+mDelFeed.getString("name"), Toast.LENGTH_SHORT).show();
			
			
			break;
		case R.id.btn_addFeedcancel:
			dismissDialog(DIALOG_DELMYFEEDS);
			break;
			
		default:
			
			break;
		}
	}
	
	public void setAllBoardsView(){
	    	
	    	mFeedView.removeAllViews();
			//推荐分类显示
	    	Cursor cursor=managedQuery(FeedsData.CategoryColumns.CONTENT_URI,null, null, null, null);
	    	
	    	int pageCount = (int)Math.ceil(((float)(cursor.getCount()+1))/Property.PAGE_SIZE_BOARD);
//	    	BoardAdapter mBoardAdapter = new BoardAdapter(MainActivity.this,R.layout.item_allboards,cursor);
	    	for(int i=0;i<pageCount;i++){
	    		GridView gv=new GridView(MainActivity.this);
	    		gv.setLayoutAnimation(controller);
	    		gv.setNumColumns(Property.COLUMN_SIZE_BOARD);
	    		gv.setAdapter(new BoardAdapter(MainActivity.this,R.layout.item_allboards,cursor,i));
	    		gv.setOnItemClickListener(gridItemClick);
	    		mFeedView.addView(gv);
	    	}
	    	mMode=MODE_ALLBOARDS;
	    }
	   
	public void delMyFeed(Bundle data){
		
		
		int id=data.getInt("id");
		
		//在我的订阅表中删除改项
		this.getContentResolver().delete(MyFeedsColumns.CONTENT_URI, MyFeedsColumns.RSS_ID+"="+id, null);
		ContentObserver mSelfObserver ;
		this.getContentResolver().query(MyFeedsColumns.CONTENT_URI, null, null, null, null)
								 .setNotificationUri(this.getContentResolver(), MyFeedsColumns.CONTENT_URI);
	
		//在总订阅中更新该项
		ContentValues values=new ContentValues();
		values.put(AllFeedsColumns.CATEGORY, data.getString("category"));
		values.put(AllFeedsColumns.ICON_NAME, data.getString("icon_name"));
		values.put(AllFeedsColumns.LINK, data.getString("link"));
		values.put(FeedsData.NAME, data.getString("name"));
		values.put(AllFeedsColumns.SELECTED, 0);
		
		this.getContentResolver().update(AllFeedsColumns.CONTENT_URI, values, AllFeedsColumns._ID+"="+id, null);
		
		//在Entry表中删除该项对应的信息
		this.getContentResolver().delete(EntryColumns.CONTENT_URI, EntryColumns.RSS_ID+"="+id, null);
		
	}
	    
	public void setAllFeedsView(String board){
	    	
	    	mFeedView.removeAllViews();
//	    	cursor=managedQuery(FeedsData.AllFeedsColumns.CONTENT_URI, null,
//	    			FeedsData.AllFeedsColumns.CATEGORY+"=?", new String[]{board}, null);
	    	Cursor cursor=this.getContentResolver().query(FeedsData.AllFeedsColumns.CONTENT_URI, null,
	    			FeedsData.AllFeedsColumns.CATEGORY+"=?", new String[]{board}, null);
	        
	    	int dataSize=cursor.getCount();
	    	if(0!=dataSize){
	    		
	    		 int pageCount = (int)Math.ceil(((float)(dataSize+1))/Property.PAGE_SIZE_ALLFEED);
	    		 mAllFeedsAdapter = new AllFeedsAdapter(MainActivity.this,R.layout.item_allfeeds,cursor);
			        for (int i=0; i<pageCount; i++) {
			        	mAllFeedsAdapter.setPage(i);
			        	GridView gv=new GridView(MainActivity.this);
			        	gv.setLayoutAnimation(controller);
			    		gv.setNumColumns(Property.COLUMN_SIZE_ALLFEED);
			    		
			    		gv.setAdapter(mAllFeedsAdapter);    		
			    		gv.setOnItemClickListener(gridItemClick);
			    		
			    		mFeedView.addView(gv);		        
			        }
	    	}
	        
	        mMode=MODE_ALLFEEDS;
	    }
	    
	public void setMyFeedsView(){
	    	
	    	mFeedView.removeAllViews();
	    	//已定的Feed显示  	 
	    	Cursor  cursor=managedQuery(FeedsData.MyFeedsColumns.CONTENT_URI,null, null, null, null);

	    	mMode=MODE_MYFEEDS;
	    	
	    	int dataSize=cursor.getCount();
	    	if(0!=dataSize){
	    			    		
	    		int pageCount = (int)Math.ceil(((float)(dataSize+1))/Property.PAGE_SIZE_MYFEED);
	 	        for (int i=0; i<pageCount; i++) {
	 	        	GridView gv=new GridView(MainActivity.this);
	 	        	gv.setLayoutAnimation(controller);
	 	    		gv.setNumColumns(Property.COLUMN_SIZE_MYFEED);
	 	    		gv.setAdapter(new FeedAdapter(MainActivity.this,R.layout.item_myfeeds,cursor,i));    
	 	    		gv.setPadding(30, 0, 0, 0);
	 	    		gv.setOnItemClickListener(gridItemClick);
	 	    		gv.setTag(pageCount);
	 	    		mFeedView.addView(gv);
	 	    		Log.i("=addView GridView=", "add");
	 	        
	 	        }
	    	}
	    }
    
	
	public void updateEntry(){
		
		Cursor cursor=managedQuery(MyFeedsColumns.CONTENT_URI,null, null, null, null);
		
		while(cursor.moveToNext()){
			 int rss_id=cursor.getInt(cursor.getColumnIndex(FeedsData.MyFeedsColumns.RSS_ID));
			 Date baseDate=null;
			if(rss_id!=0){
				 String link=cursor.getString(cursor.getColumnIndex(MyFeedsColumns.LINK));
				Cursor cursor_entry=managedQuery(EntryColumns.CONTENT_URI,null,EntryColumns.RSS_ID+"="+rss_id ,
						null, EntryColumns.PUBDATE+" DESC");

				if(0!=cursor_entry.getCount()){
					cursor_entry.moveToNext();
					baseDate=PubDateParser.parse(cursor_entry.getString(cursor_entry.getColumnIndex(EntryColumns.PUBDATE))); 
				}
				AsycItemFreshLoder.rssRefresh(link,this,rss_id, baseDate);

			}
		
	}
		handler.sendEmptyMessage(UPDATE_ENTRY_OK);
	}
	
	
	
}
 
    